/*
 * usart.c
 *
 * Created: 05.09.2012 16:06:06
 *  Author: bardbakk
 */
#define F_CPU 11059200
#include "USART.h"
#include <avr/io.h> 
#include <avr/interrupt.h>
#include <stdio.h>

void USART_init(unsigned int baudrate){
	
	unsigned int baud;
	baud = ((F_CPU)/(16UL*baudrate)) - 1;
	
	cli();
	UBRR0H = (unsigned char)(baudrate>>8);
	UBRR0L = (unsigned char)baudrate;
	
	//Enables receive, transmit and receive interrupt
	UCSR0B = (1<<RXEN0)|(1<<TXEN0)/*|(1<<RXCIE0)*/;
	
	//Enables use of UCSRC and sets frame format: 2 stop bits, 8 bits. 
	UCSR0C = (1<<USBS0)|(3<<UCSZ00);
		
	sei();
	
	fdevopen(USART_transmit, USART_receive);
}

int USART_transmit(unsigned char data)
{
	while(!(UCSR0A & (1<<UDRE0)))
	{
	}
	UDR0=data;
	return 0;
}

unsigned char USART_receive()
{
	char receivedByte = UDR1;
	return receivedByte;
}



ISR(USART1_RXC_vect, ISR_BLOCK)
{
	char receivedByte = USART_receive();
	USART_transmit(receivedByte);
}